<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Cache;
use think\Db;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{
    protected $noNeedLogin = ['index_api','index_api2','index_api3','index_api4'];
    /**
     * 查看
     */
    public function index()
    {
        $this->view->assign([
            'report'         => $this->request->domain().'/#/report',
            'flow'        => $this->request->domain().'/#/flow',
        ]);
        return $this->view->fetch();
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $dbTableList = Db::query("SHOW TABLE STATUS");
        $addonList = get_addon_list();
        $totalworkingaddon = 0;
        $totaladdon = count($addonList);
        foreach ($addonList as $index => $item) {
            if ($item['state']) {
                $totalworkingaddon += 1;
            }
        }
        $this->view->assign([
            'totaluser'         => User::count(),
            'totaladdon'        => $totaladdon,
            'totaladmin'        => Admin::count(),
            'totalcategory'     => \app\common\model\LitestoreCategory::count(),
            'todayusersignup'   => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin'    => User::whereTime('logintime', 'today')->count(),
            'sevendau'          => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'         => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'          => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'          => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums'       => count($dbTableList),
            'dbsize'            => array_sum(array_map(function ($item) {
                return $item['Data_length'] + $item['Index_length'];
            }, $dbTableList)),
            'totalworkingaddon' => $totalworkingaddon,
            'attachmentnums'    => Attachment::count(),
            'attachmentsize'    => Attachment::sum('filesize'),
            'picturenums'       => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize'       => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
        ]);

        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));

        //访问量
        $visits_column = [];
        $visits_starttime = Date::unixtime('day', -6);
        $visits_endtime = Date::unixtime('day', 0, 'end');
        $list1 = Db("visits")->where('everydate', 'between time', [$visits_starttime, $visits_endtime])
            ->field('everydate, COUNT(*) AS number')
            ->group('everydate')
            ->select();
        for ($time = $visits_starttime; $time <= $visits_endtime;) {
            $visits_column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $visits_list = array_fill_keys($visits_column, 0);
        foreach ($list1 as $k => $v) {
            $visits_list[$v['everydate']] = $v['number'];
        }
        $this->assignconfig('visits_column', array_keys($visits_list));
        $this->assignconfig('visits_data', array_values($visits_list));

        //博主销售金额
        $column = [];
        $list1 = Db("litestore_order")->where('pay_time', 'between time', [$starttime, $endtime])->where('parent_user_id>0')
            ->field('pay_time,SUM(pay_price) AS pay_price, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m-%d") AS pay_date')
            ->group('pay_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $list = array_fill_keys($column, 0);
        foreach ($list1 as $k => $v) {
            $list[$v['pay_date']] = $v['pay_price'];
        }
        $this->assignconfig('blogger_sales_amount_column', array_keys($list));
        $this->assignconfig('blogger_sales_amount_data', array_values($list));

        //网站自助销售金额
        $column = [];
        $list1 = Db("litestore_order")->where('pay_time', 'between time', [$starttime, $endtime])->where('parent_user_id=0')
            ->field('pay_time,SUM(pay_price) AS pay_price, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m-%d") AS pay_date')
            ->group('pay_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $list = array_fill_keys($column, 0);
        foreach ($list1 as $k => $v) {
            $list[$v['pay_date']] = $v['pay_price'];
        }
        $this->assignconfig('website_sales_amount_column', array_keys($list));
        $this->assignconfig('website_sales_amount_data', array_values($list));

        //下单率
        $order_nums = Db("litestore_order")->where('pay_time', 'between time', [$starttime, $endtime])->where('parent_user_id=0')
            ->field('pay_time,COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m-%d") AS pay_date')
            ->group('pay_date')
            ->select();
        $order_list = array_fill_keys($visits_column, 0);
        foreach ($order_nums as $k => $v) {
            $order_list[$v['pay_date']] = empty($visits_list[$v['pay_date']]) ? 0 :round($v['nums'] / $visits_list[$v['pay_date']],4) * 100;
        }
        $this->assignconfig('order_rate_column', array_keys($order_list));
        $this->assignconfig('order_rate_data', array_values($order_list));

        return $this->view->fetch();
    }

    /**
     * 统计-交易概况-最上面数值统计，最下面商品、分类排行
     */
    public function index_api()
    {
//        $key = 'dashboard_data';
//        Cache::rm($key);
//        $data = Cache::get($key);
//        if(!empty($data)){
//            return json_encode(['code'=>1,'data'=>$data]);
//        }
        //网站总销售金额、支付笔数、利润总额
        //网站总销售额:网站所有成功支付的订单金额之和 (不剔除退款订单)
        //支付笔数:网站所有成功支付的订单数，一个订单对应唯一一个订单号。(收货完成计入支付订单;不剔除退款订单。)
        //利润: 网站所有成功支付的订单金额之和减去成本价再减去博主分佣金额
//        $where['id'] = ['in','19,20,21,22'];
        $where['pay_status'] = '20';
        $data['all_order_money'] = Db::name("litestore_order")->where($where)->sum('pay_price');
        $data['all_order_pay_num'] = Db::name("litestore_order")->where($where)->count();
        $dd = Db::name("litestore_order")->alias('a')->join('litestore_order_goods b','a.id=b.order_id')
            ->where($where)->field('SUM(b.total_price-b.cost_price*b.total_num-a.rebates) as all_order_profit')->find();
        $data['all_order_profit'] = $dd['all_order_profit'];

        //网站自主销售额、支付笔数、利润总额
        $where = [];
//        $where['a.id'] = ['in','74,75,78,79'];
        $where['pay_status'] = '20';
        $where['parent_user_id'] = 0;
        $data['web_order_money'] = Db::name("litestore_order")->alias('a')->where($where)->sum('pay_price');
        $data['web_order_pay_num'] = Db::name("litestore_order")->alias('a')->where($where)->count();
        $dd = Db::name("litestore_order")->alias('a')->join('litestore_order_goods b','a.id=b.order_id')
            ->where($where)->field('SUM(b.total_price-b.cost_price*b.total_num-a.rebates) as all_order_profit')->find();
        $data['web_order_profit'] = $dd['all_order_profit'];

        //博主销售额、支付笔数、利润总额
        //博主总销售额:分佣订单成功支付的订单金额之和 (不剔除退款订单)
        //支付笔数:分佣订单成功支付的订单数，一个订单对应唯一一个订单号。(收货完成计入支付订单;不剔除退款订单。)
        //利润:分佣订单成功支付的订单金额之和减去成本价
        $where = [];
//        $where['a.id'] = ['in','74,75,78,79'];
        $where['pay_status'] = '20';
        $where['parent_user_id'] = ['>',0];
        $data['blogger_order_money'] = Db::name("litestore_order")->alias('a')->where($where)->sum('pay_price');
        $data['blogger_order_pay_num'] = Db::name("litestore_order")->alias('a')->where($where)->count();
        $dd = Db::name("litestore_order")->alias('a')->join('litestore_order_goods b','a.id=b.order_id')
            ->where($where)->field('SUM(b.total_price-b.cost_price*b.total_num-a.rebates) as all_order_profit')->find();
        $data['blogger_order_profit'] = $dd['all_order_profit'];

        //营销总销售额、支付笔数、利润总额
        //营销总销售额: 活动订单成功支付的订单金额之和 (不剔除退款订单)
        //支付笔数:活动订单成功支付的订单数，一个订单对应唯一一个订单号。(收货完成计入支付订单;不剔除退款订单。)
        //利润: 活动订单成功支付的订单金额之和减去成本价
        $where = [];
//        $where['a.id'] = ['in','38,39,50'];
        $where['pay_status'] = '20';
        $where1 = "code <> '' or activity_rule <> ''";
        $data['activity_order_money'] = Db::name("litestore_order")->alias('a')->where($where)->where($where1)->sum('pay_price');
        $data['activity_order_pay_num'] = Db::name("litestore_order")->alias('a')->where($where)->where($where1)->count();
        $dd = Db::name("litestore_order")->alias('a')->join('litestore_order_goods b','a.id=b.order_id')
            ->where($where)->where($where1)->field('SUM(b.total_price-b.cost_price*b.total_num-a.rebates) as all_order_profit')->find();
        $data['activity_order_profit'] = $dd['all_order_profit'];

        //商品销售额排行（前十）
        $sql = "SELECT goods_id,sum(goods_sales*goods_price) as sales_money FROM fa_litestore_goods_spec WHERE  goods_sales>0 group by goods_id order by sales_money desc limit 10";
        $goods_sort = Db::query($sql);
        $goods_ids = array_column($goods_sort,'goods_id');
        $goods_list = Db::name("litestore_goods")->field('goods_id,goods_name')->where('goods_id','in',$goods_ids)->select();
        $goods_list = array_column($goods_list,null,'goods_id');
        foreach ($goods_sort as $k=>$v){
            $goods_sort[$k]['goods_name'] = $goods_list[$v['goods_id']]['goods_name'];
        }
        $data['goods_sales_money_sort'] = $goods_sort;

        //商品分类销售额
        $sql = "SELECT category_id,sum(goods_sales*goods_price) as sales_money FROM fa_litestore_goods_spec as a join fa_litestore_goods as b on a.goods_id=b.goods_id WHERE  goods_sales>0 group by category_id order by sales_money desc";
        $category_sort = Db::query($sql);
        $total_sales_money = 0;
        foreach ($category_sort as $v){
            $total_sales_money += $v['sales_money'];
        }
//        halt($total_sales_money);
        $category_ids = array_column($category_sort,'category_id');
        $category_list = Db::name("litestore_category")->field('id,name')->where('id','in',$category_ids)->select();
        $category_list = array_column($category_list,null,'id');
        $bili_all = 0;
        foreach ($category_sort as $k=>$v){
            $category_sort[$k]['name'] = $category_list[$v['category_id']]['name'];
            $bili = round($v['sales_money'] / $total_sales_money,4) * 100;
            $category_sort[$k]['bili'] = strval($bili);
            $bili_all += $bili;
        }
        if($bili_all != 100){
            $diff_bili = 100 - $bili_all;
            foreach ($category_sort as $k=>$v){
                if($k == 0){
                    $category_sort[$k]['bili'] = strval($v['bili'] + $diff_bili);
                }
            }
        }
        $data['category_sales_money_sort'] = $category_sort;

//        Cache::set($key,$data,300);
        return json_encode(['code'=>1,'data'=>$data]);
    }

    /**
     * 统计-交易概况-柱状图
     */
    public function index_api2()
    {
        $params = $this->request->request();

        $cache_key = md5(json_encode($params));
        $data = Cache::get($cache_key);
        if(!empty($data)){
            return json_encode(['code'=>1,'data'=>$data]);
        }

        //周（天）、月（天）、年（月）
        if($params['time_type'] == 'week'){
            $starttime = Date::unixtime('day', -6);//最近7天
            $endtime = Date::unixtime('day', 0, 'end');
            $where['pay_time'] = ['between time',[$starttime, $endtime]];
        }elseif($params['time_type'] == 'month'){
//            $starttime = strtotime(date('Y-m').'-1');//当月开始
//            $endtime = strtotime(date('Y-m-d'));//当月结束
            $starttime = Date::unixtime('day', -30);//最近30天
            $endtime = Date::unixtime('day', 0, 'end');
            $where['pay_time'] = ['between time',[$starttime, $endtime]];
        }elseif($params['time_type'] == 'year'){
//            $starttime = strtotime(date('Y').'-1');//当年开始
//            $endtime = strtotime(date('Y-m-d').' 23:59:59');//当年结束
            $starttime = Date::unixtime('month', -11);//最近12个月
            $endtime = Date::unixtime('month', 0, 'end');
            $where['pay_time'] = ['between time',[$starttime, $endtime]];
        }else{
            if(empty($params['start_time']) || empty($params['end_time'])){
                return json_encode(['code'=>1,'msg'=>'Date cannot be empty','data'=>[]]);
            }
            $starttime = strtotime($params['start_time'].' 00:00:00');
            $endtime = strtotime($params['end_time'].' 23:59:59');
            $where['pay_time'] = ['between time',[$starttime, $endtime]];
        }
        $where1 = [];
        if($params['type'] == 1){
            //1=网站销售金额,2=网站自助销售金额,3=博主销售金额,4=营销销售金额

        }elseif($params['type'] == 2){
            //网站自助销售金额
            $where['parent_user_id'] = '0';
        }elseif($params['type'] == 3){
            //博主销售金额
            $where['parent_user_id'] = ['>','0'];
        }elseif($params['type'] == 4){
            //营销销售金额
            $where1 = "code <> '' or activity_rule <> ''";
        }

        if($params['time_type'] == 'year'){
            $column = [];
            $list1 = Db::name("litestore_order")->where($where)->where($where1)
                ->field('pay_time,SUM(pay_price) AS pay_price, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m") AS pay_month')
                ->group('pay_month')
                ->select();
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("Y-m", $time);
                $time += 86400*31;
            }
            $list = array_fill_keys($column, 0);
            foreach ($list1 as $k => $v) {
                $list[$v['pay_month']] = $v['pay_price'];
            }
        }else{
            $column = [];
            $list1 = Db::name("litestore_order")->where($where)->where($where1)
                ->field('pay_time,SUM(pay_price) AS pay_price, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m-%d") AS pay_date')
                ->group('pay_date')
                ->select();
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("Y-m-d", $time);
                $time += 86400;
            }
            $list = array_fill_keys($column, 0);
            foreach ($list1 as $k => $v) {
                $list[$v['pay_date']] = $v['pay_price'];
            }
        }
        $data['column']= array_keys($list);
        $data['data']= array_values($list);

        Cache::set($cache_key,$data,300);
        return json_encode(['code'=>1,'data'=>$data]);
    }

    /**
     * 统计-流量概况-最上面数值统计，最下面商品、分类排行
     */
    public function index_api3()
    {
//        $key = 'dashboard_data3';
//        Cache::rm($key);
//        $data = Cache::get($key);
//        if(!empty($data)){
//            return json_encode(['code'=>1,'data'=>$data]);
//        }

        //网站总点击量:网站被访问次数。
        //下单率:支付成功的总人数/所有访客数x100%
        $data['all_visits'] = Db::name("visits")->whereTime('everydate','today')->where('type',1)->count();
        $all_order_pay_num = Db::name("litestore_order")->where('pay_status','20')->whereTime('pay_time','today')->count();
        $data['all_rate'] = $all_order_pay_num/$data['all_visits']*100;

        //博主营销点击量:带有博主ID链接的被访问次数。
        //下单率:带有博主ID链接的支付成功的总人数/所有访客数x100%
        $data['blogger_visits'] = Db::name("visits")->whereTime('everydate','today')->where('type',2)->count();
        $blogger_order_pay_num = Db::name("litestore_order")->where('pay_status','20')->whereTime('pay_time','today')->where('parent_user_id > 0')->count();
        $data['blogger_rate'] = empty($data['blogger_visits']) ? 0 :$blogger_order_pay_num/$data['blogger_visits']*100;

        //网站自主点击量:非带有博主ID链接的被访问次数。
        //下单率:非带有博主ID链接支付成功的总人数/所有访客数x100%
        $data['web_visits'] = $data['all_visits'] - $data['blogger_visits'];
        $web_order_pay_num = Db::name("litestore_order")->where('pay_status','20')->whereTime('pay_time','today')->where('parent_user_id','0')->count();
        $data['web_rate'] = empty($data['web_visits']) ? 0 :$web_order_pay_num/$data['web_visits']*100;

        //产品点击量排行（前10）
        $sql = "SELECT goods_id,check_num FROM fa_litestore_goods WHERE check_num>0  order by check_num desc limit 10";
        $goods_sort = Db::query($sql);
        $goods_ids = array_column($goods_sort,'goods_id');
        $goods_list = Db::name("litestore_goods")->field('goods_id,goods_name')->where('goods_id','in',$goods_ids)->select();
        $goods_list = array_column($goods_list,null,'goods_id');
        foreach ($goods_sort as $k=>$v){
            $goods_sort[$k]['goods_name'] = $goods_list[$v['goods_id']]['goods_name'];
        }
        $data['goods_check_sort'] = $goods_sort;

        //产品下单率排行（前10）
        $sql1 = "SELECT goods_id,ROUND(sales_actual/check_num,4) as order_rate FROM fa_litestore_goods WHERE check_num>0 order by order_rate desc limit 10";
        $goods_sort1 = Db::query($sql1);
        $goods_ids1 = array_column($goods_sort1,'goods_id');
        $goods_list1 = Db::name("litestore_goods")->field('goods_id,goods_name')->where('goods_id','in',$goods_ids1)->select();
        $goods_list1 = array_column($goods_list1,null,'goods_id');
        foreach ($goods_sort1 as $k=>$v){
            $goods_sort1[$k]['goods_name'] = $goods_list1[$v['goods_id']]['goods_name'];
            $goods_sort1[$k]['order_rate'] = sprintf("%.2f",$v['order_rate'] * 100);
        }
        $data['goods_order_rate_sort'] = $goods_sort1;

        //产品分类点击量排行
        $sql = "SELECT category_id,sum(check_num) as all_check_num FROM fa_litestore_goods WHERE check_num>0 group by category_id order by all_check_num desc";
        $category_sort = Db::query($sql);
        $total_check_num = 0;
        foreach ($category_sort as $v){
            $total_check_num += $v['all_check_num'];
        }
        $category_ids = array_column($category_sort,'category_id');
        $category_list = Db::name("litestore_category")->field('id,name')->where('id','in',$category_ids)->select();
        $category_list = array_column($category_list,null,'id');
        $bili_all = 0;
        foreach ($category_sort as $k=>$v){
            $category_sort[$k]['name'] = $category_list[$v['category_id']]['name'];
            $bili = round($v['all_check_num'] / $total_check_num,4) * 100;
            $category_sort[$k]['bili'] = $bili;
            $bili_all += $bili;
        }
        if($bili_all != 100){
            $diff_bili = 100 - $bili_all;
            foreach ($category_sort as $k=>$v){
                if($k == 0){
                    $category_sort[$k]['bili'] = $v['bili'] + $diff_bili;
                }
            }
        }
        $data['category_check_sort'] = $category_sort;

        //产品分类下单率排行
        $sql1 = "SELECT category_id,SUM(ROUND(sales_actual/check_num,4)) as all_order_rate FROM fa_litestore_goods WHERE check_num>0 group by category_id order by all_order_rate desc";
        $category_sort1 = Db::query($sql1);
        $total_check_num1 = 0;
        foreach ($category_sort1 as $v){
            $total_check_num1 += $v['all_order_rate'];
        }
        $category_ids1 = array_column($category_sort1,'category_id');
        $category_list1 = Db::name("litestore_category")->field('id,name')->where('id','in',$category_ids1)->select();
        $category_list1 = array_column($category_list1,null,'id');
        $bili_all1 = 0;
        foreach ($category_sort1 as $k=>$v){
            $category_sort1[$k]['name'] = $category_list1[$v['category_id']]['name'];
            $bili1 = round($v['all_order_rate'] / $total_check_num1,4) * 100;
            $category_sort1[$k]['bili'] = $bili1;
            $bili_all1 += $bili1;
        }
        if($bili_all1 != 100){
            $diff_bili1 = 100 - $bili_all1;
            foreach ($category_sort1 as $k=>$v){
                if($k == 0){
                    $category_sort1[$k]['bili'] = $v['bili'] + $diff_bili1;
                }
            }
        }
        $data['category_order_rate_sort'] = $category_sort1;

        //博主营销点击量排行
        $sql = "SELECT blogger_id,COUNT(ip) as num FROM fa_visits_blogger group by blogger_id order by num desc limit 10";
        $blogger_sort = Db::query($sql);
        $user_ids = array_column($blogger_sort,'blogger_id');
        $user_list = Db::name("user")->field('id,nickname')->where('id','in',$user_ids)->select();
        $user_list = array_column($user_list,null,'id');
        foreach ($blogger_sort as $k=>$v){
            $blogger_sort[$k]['nickname'] = $user_list[$v['blogger_id']]['nickname'];
        }
        $data['blogger_check_sort'] = $blogger_sort;

        //博主营销下单率排行（前10）
        $sql1 = "SELECT parent_user_id,COUNT(id) as num FROM fa_litestore_order where parent_user_id>0 group by parent_user_id order by num desc limit 10";
        $blogger_sort = Db::query($sql1);
        $user_ids = array_column($blogger_sort,'parent_user_id');
        $user_list = Db::name("user")->field('id,nickname')->where('id','in',$user_ids)->select();
        $user_list = array_column($user_list,null,'id');
        foreach ($blogger_sort as $k=>$v){
            $blogger_sort[$k]['nickname'] = $user_list[$v['parent_user_id']]['nickname'];
        }
        $data['blogger_order_sort'] = $blogger_sort;


//        Cache::set($key,$data,300);
        return json_encode(['code'=>1,'data'=>$data]);
    }

    //统计-流量概况-折线图
    public function index_api4()
    {
        $params = $this->request->request();

//        $cache_key = md5(json_encode($params));
//        $data = Cache::get($cache_key);
//        if(!empty($data)){
//            return json_encode(['code'=>1,'data'=>$data]);
//        }

        //周（天）、月（天）、年（月）
        if($params['time_type'] == 'week'){
            $starttime = Date::unixtime('day', -6);//最近7天
            $endtime = Date::unixtime('day', 0, 'end');
            $where_visits['everydate'] = ['between time',[date('Y-m-d',$starttime), date('Y-m-d',$endtime)]];
            $where_order['pay_time'] = ['between time',[$starttime, $endtime]];
        }elseif($params['time_type'] == 'month'){
//            $starttime = strtotime(date('Y-m').'-1');//当月开始
//            $endtime = strtotime(date('Y-m-d'));//当月结束
            $starttime = Date::unixtime('day', -30);//最近30天
            $endtime = Date::unixtime('day', 0, 'end');
            $where_visits['everydate'] = ['between time',[date('Y-m-d',$starttime), date('Y-m-d',$endtime)]];
            $where_order['pay_time'] = ['between time',[$starttime, $endtime]];
        }elseif($params['time_type'] == 'year'){
//            $starttime = strtotime(date('Y').'-1');//当年开始
//            $endtime = strtotime(date('Y-m-d').' 23:59:59');//当年结束
            $starttime = Date::unixtime('month', -11);//最近12个月
            $endtime = Date::unixtime('month', 0, 'end');
            $where_visits['everydate'] = ['between time',[date('Y-m-d',$starttime), date('Y-m-d',$endtime)]];
            $where_order['pay_time'] = ['between time',[$starttime, $endtime]];
        }else{
            if(empty($params['start_time']) || empty($params['end_time'])){
                return json_encode(['code'=>1,'msg'=>'Date cannot be empty','data'=>[]]);
            }
            $starttime = $params['start_time'];
            $endtime = $params['end_time'];
            $where_visits['everydate'] = ['between time',[$starttime, $endtime]];
            $where_order['pay_time'] = ['between time',[$starttime, $endtime]];
            $starttime = strtotime($starttime);
            $endtime = strtotime($endtime);
        }

        if($params['type'] == 1){
            //网站总点击量:网站被访问次数。
            //下单率:支付成功的总人数/所有访客数x100%
            $where_visits['type'] = 1;
        }elseif($params['type'] == 2){
            //网站自主点击量:非带有博主ID链接的被访问次数。
            //下单率:非带有博主ID链接支付成功的总人数/所有访客数x100%
            $where_visits['type'] = 1;
            $where_order['parent_user_id'] = '0';
        }elseif($params['type'] == 3){
            //博主营销点击量:带有博主ID链接的被访问次数。
            //下单率:带有博主ID链接的支付成功的总人数/所有访客数x100%
            $where_visits['type'] = 2;
            $where_order['parent_user_id'] = ['>','0'];
        }

        if($params['time_type'] == 'year'){
            //点击量
            $column = [];
            $list1 = Db::name("visits")->where($where_visits)
                ->field('ip,COUNT(ip) AS num, DATE_FORMAT(everydate, "%Y-%m") AS pay_month')
                ->group('pay_month')
                ->select();
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("Y-m", $time);
                $time += 86400*31;
            }
            if($params['type'] == 2){
                unset($where_visits['type']);
                $where_visits['type'] = 2;
                $list2 = Db::name("visits")->where($where_visits)
                    ->field('ip,COUNT(ip) AS num, DATE_FORMAT(everydate, "%Y-%m") AS pay_month')
                    ->group('pay_month')
                    ->select();
                $list2 = array_column($list2,null,'pay_month');
            }
            //下单率
            $order_pay_num = Db::name("litestore_order")->where('pay_status','20')->where($where_order)
                ->field('pay_time,COUNT(id) AS order_num, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m") AS pay_month')
                ->group('pay_month')
                ->select();
            $order_pay_num = array_column($order_pay_num,null,'pay_month');
            $list = $list_rate = array_fill_keys($column, 0);
            foreach ($list1 as $k => $v) {
                if($params['type'] == 2 && array_key_exists($v['pay_month'],$list2)){
                    $list[$v['pay_month']] = $v['num'] - $list2[$v['pay_month']]['num'];
                }else{
                    $list[$v['pay_month']] = $v['num'];
                }

                if(array_key_exists($v['pay_month'],$order_pay_num)){
                    $list_rate[$v['pay_month']] = sprintf("%.2f",$order_pay_num[$v['pay_month']]['order_num'] / $list[$v['pay_month']] * 100);
                }
            }
        }else{
            $column = [];
            $list1 = Db::name("visits")->where($where_visits)
                ->field('ip,COUNT(ip) AS num, DATE_FORMAT(everydate, "%Y-%m-%d") AS pay_date')
                ->group('pay_date')
                ->select();
            for ($time = $starttime; $time <= $endtime;) {
                $column[] = date("Y-m-d", $time);
                $time += 86400;
            }
            if($params['type'] == 2){
                unset($where_visits['type']);
                $where_visits['type'] = 2;
                $list2 = Db::name("visits")->where($where_visits)
                    ->field('ip,COUNT(ip) AS num, DATE_FORMAT(everydate, "%Y-%m-%d") AS pay_date')
                    ->group('pay_date')
                    ->select();
                $list2 = array_column($list2,null,'pay_date');
            }
            //下单率
            $order_pay_num = Db::name("litestore_order")->where('pay_status','20')->where($where_order)
                ->field('pay_time,COUNT(id) AS order_num, DATE_FORMAT(FROM_UNIXTIME(pay_time), "%Y-%m-%d") AS pay_date')
                ->group('pay_date')
                ->select();
            $order_pay_num = array_column($order_pay_num,null,'pay_date');
            $list = $list_rate = array_fill_keys($column, 0);
            foreach ($list1 as $k => $v) {
                if($params['type'] == 2 && array_key_exists($v['pay_date'],$list2)){
                    $list[$v['pay_date']] = $v['num'] - $list2[$v['pay_date']]['num'];
                }else{
                    $list[$v['pay_date']] = $v['num'];
                }

                if(array_key_exists($v['pay_date'],$order_pay_num)){
                    $list_rate[$v['pay_date']] = sprintf("%.2f",$order_pay_num[$v['pay_date']]['order_num'] / $list[$v['pay_date']] * 100);
                }
            }
        }
        $data['check']['column']= array_keys($list);
        $data['check']['data']= array_values($list);

        $data['rate']['column']= array_keys($list_rate);
        $data['rate']['data']= array_values($list_rate);
//        Cache::set($cache_key,$data,300);
        return json_encode(['code'=>1,'data'=>$data]);
    }

}
